#include "RenderPch.h"

#include "FontManager.h"
#include "Font.h"
#include "RenderFacade.h"
#include "XmlUtil.h"

FontManager::FontManager(void)
{
	m_hmapFont.clear();
}

FontManager::~FontManager(void)
{
	UnInit();
}

void FontManager::Init( const char * fileName )
{
	XmlDocument doc;
	if( doc.LoadFile( fileName ) )
	{
		XmlNode * fontListNode = doc.GetChildNode( "font_list" );

		int fontNodeCount = fontListNode->GetChildNodeCount( "font" );
		for( int cnt = 0; cnt < fontNodeCount; cnt++ )
		{
			XmlNode * fontNode = fontListNode->GetChildNode( "font", cnt );

			std::string fontID = fontNode->GetAttribute( "id" );
			std::string fontName = fontNode->GetAttribute( "name" );
			int fontHeight = atoi( fontNode->GetAttribute( "height" ) );
			int fontWidth = atoi( fontNode->GetAttribute( "width" ) );
			int fontWeight = atoi( fontNode->GetAttribute( "weight" ) );

			BOOL italic = FALSE;
			std::string italicStr = fontNode->GetAttribute( "italic" );
			if( italicStr == "true" )
			{
				italic = TRUE;
			}

			D3DXFONT_DESC desc;
			memset( &desc, 0, sizeof( D3DXFONT_DESC ) );

			desc.CharSet = DEFAULT_CHARSET;
			strcpy_s( desc.FaceName, sizeof( desc.FaceName ), fontName.c_str() );
			desc.Height = fontHeight;
			desc.Width = fontWidth;
			desc.Weight = fontWeight;
			desc.Italic = italic;

			desc.MipLevels = 0;
			desc.OutputPrecision = OUT_DEFAULT_PRECIS;
			desc.PitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
			desc.Quality = ANTIALIASED_QUALITY;

			AddFont( fontID.c_str(), desc );
		}
	}
}

void FontManager::UnInit()
{
	if(m_hmapFont.size() > 0)
	{
		FontHashMapItor Begin = m_hmapFont.begin();
		for(; Begin != m_hmapFont.end(); )
		{
			Font* pFont = Begin->second;
			delete pFont;

			++Begin;
		}

		m_hmapFont.clear();
	}
}

bool FontManager::AddFont( const char* fontID, D3DXFONT_DESC & desc )
{
	Font* pFont = GetFont( fontID );
	if( pFont )
	{
		return false;
	}

	pFont = new Font();
	pFont->m_FontDesc = desc;

	HRESULT hr = D3DXCreateFontIndirect( RenderFacade::GetInstance()->GetDxDevice(), &desc, &pFont->m_lpFont );
	if( FAILED( hr ) )
	{
		delete pFont;
		return false;
	}

	m_hmapFont[ fontID ] = pFont;

	return true;
}

Font * FontManager::GetFont( const char * fontID )
{
	FontHashMapItor Find = m_hmapFont.find( fontID );
	if( Find != m_hmapFont.end() )
	{
		return Find->second;
	}

	return NULL;
}